/*
 * This class will handle request in getting Restaurant information from Server
 * All the information would be wrapped in Meal Class object
 */

package com.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.configuration.Configuration;
import com.object.Restaurant;
import com.user.JSONParser;

public class RestaurantFetch {
	
    
	//URL for fetching data
	// fetchRestaurantByIdURL 	: fetchRestaurantById(),fetchRestaurantNameById()
	// fetchAllRestaurantURL	: fetchAllRestaurant()
    private static String fetchRestaurantByIdURL 	= "http://128.199.214.245/android/RestaurantFetch/fetch_restaurant_by_id.php";
    private static String fetchAllRestaurantURL 	= "http://128.199.214.245/android/RestaurantFetch/fetch_all_restaurant.php";

    //Keys for the Json field
    /*
     * KEY_STATUS shows the status of the request
     * 0 : Fail to get restaurant
     * 1 : Successfully in getting restaurant
     */
	private String KEY_ID				= "ID";
    private String KEY_STATUS 			= "STATUS";
    private String KEY_NAME 			= "NAME";
    private String KEY_ADDRESS 			= "ADDRESS";
    private String KEY_TELEPHONE 		= "TELEPHONE";
    private String KEY_OPEN_HOURS 		= "OPEN_HOURS";
    private String KEY_DESCRIPTION 		= "DESCRIPTION";
    private String KEY_PROFILE_PICTURE 	= "PROFILE_PICTURE";
    private String KEY_TAG				= "TAG";
    private String KEY_COUPON			= "COUPON";
    
    private String KEY_NUMBER = "NUMBER";		//Returned by server telling how many restaurants 
    
    private String FAIL 	= "0";
    private String SUCCESS 	= "1";
    
    //For making httpRequest
    private JSONParser jsonParser;
    private JSONObject result;
    List<NameValuePair> params;
    
  //Constructor
    public RestaurantFetch(){
        jsonParser = new JSONParser();
    }
    
    /*
	 * fetchRestaurantById function will return an Restaurant object based on Restaurant id entered
	 * - non-null	: Data of the Restaurant with id = id
	 * - null		: No such Restaurant
	 */
	public Restaurant fetchRestaurantById(int id){
		//Get Json object
		// Building Parameters
        params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("id",Integer.toString(id)));
        
        //Start a new thread and use POST method to send telephone and passcode to authURL
        //Start a new thread to attempt Login (requirement when connecting online)
		Thread attemptThread = new Thread(new Runnable(){  
			public void run(){  
				result = jsonParser.makeHttpRequest(fetchRestaurantByIdURL,"POST",params);
			}
		});  
		attemptThread.start();
		
		while(attemptThread.isAlive()){
			//Wait for server response
		}
		
		//Parse the json object
		try {
			if(result.getString(KEY_STATUS) != null){
				//Able to get response from server
				if(result.getString(KEY_STATUS).equalsIgnoreCase(SUCCESS)){
					//Successful in finding the Restaurant
					if(Configuration.showLog){
						Log.d("RestaurantFetch","fetchRestaurantById - Restaurant found");
					}
					
					// Store information to object
					String name 			= result.getString(KEY_NAME);
					String address 			= result.getString(KEY_ADDRESS);
					String telephone		= result.getString(KEY_TELEPHONE);
					String open_hours		= result.getString(KEY_OPEN_HOURS);
					String description 		= result.getString(KEY_DESCRIPTION);
					String profile_picture 	= result.getString(KEY_PROFILE_PICTURE);
					String tag				= result.getString(KEY_TAG);
					String coupon			= result.getString(KEY_COUPON);
					
					Restaurant restaurant = new Restaurant(id,name,address,telephone,open_hours,description,profile_picture,tag,coupon);					
					
					return restaurant;
					
				}else{
					//Fail to find such restaurant
					if(Configuration.showLog){
						Log.d("RestaurantFetch","fetchRestaurantById - Unable to find restaurant");
					}
				}
			}else{
				//unable to get response from server
				if(Configuration.showLog){
					Log.d("RestaurantFetch","fetchRestaurantById - Unable to get response from server");
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			if(Configuration.showLog){
				Log.d("RestaurantFetch","fetchRestaurantById - Exception");
			}
		}

		return null;
	}
	
	public List<Restaurant> fetchAllRestaurant(){
		// Building Parameters
        params = new ArrayList<NameValuePair>();
        //No parameter
        //params.add(new BasicNameValuePair("id",Integer.toString(id)));
        
        //Start a new thread and use POST method to send telephone and passcode to authURL
        //Start a new thread to attempt Login (requirement when connecting online)
		Thread attemptThread = new Thread(new Runnable(){  
			public void run(){  
				result = jsonParser.makeHttpRequest(fetchAllRestaurantURL,"POST",params);
			}
		});  
		attemptThread.start();
		
		while(attemptThread.isAlive()){
			//Wait for server response
		}
		
		//Parse the json object
		try {
			if(result.getString(KEY_STATUS) != null){
				//Able to get response from server
				if(result.getString(KEY_STATUS).equalsIgnoreCase(SUCCESS)){
					//Successful in finding the Restaurant
					if(Configuration.showLog){
						Log.d("RestaurantFetch","fetchAllRestaurant - Restaurant found");
					}
					
					int numberOfRestaurant = Integer.parseInt(result.getString(KEY_NUMBER));
					
					List <Restaurant> restaurantList = new ArrayList<Restaurant>();
					
					JSONArray idArray 				= result.getJSONArray(KEY_ID);
					JSONArray nameArray 			= result.getJSONArray(KEY_NAME);
					JSONArray addressArray 			= result.getJSONArray(KEY_ADDRESS);
					JSONArray telephoneArray 		= result.getJSONArray(KEY_TELEPHONE);
					JSONArray openHoursArray 		= result.getJSONArray(KEY_OPEN_HOURS);
					JSONArray descriptionArray 		= result.getJSONArray(KEY_DESCRIPTION);
					JSONArray profilePictureArray 	= result.getJSONArray(KEY_PROFILE_PICTURE);
					JSONArray tagArray 				= result.getJSONArray(KEY_TAG);
					JSONArray couponArray 			= result.getJSONArray(KEY_COUPON);
					
					for(int i=0;i<numberOfRestaurant;i++){
						// Store information to object
						
						int	id					= Integer.parseInt(idArray.getString(i));
						String name 			= nameArray.getString(i);
						String address 			= addressArray.getString(i);
						String telephone		= telephoneArray.getString(i);
						String openHours		= openHoursArray.getString(i);
						String description 		= descriptionArray.getString(i);
						String profilePicture 	= profilePictureArray.getString(i);
						String tag				= tagArray.getString(i);
						String coupon			= couponArray.getString(i);
						
						Restaurant restaurant = new Restaurant(id,name,address,telephone,openHours,description,profilePicture,tag,coupon);
						restaurantList.add(restaurant);
						
					}
					
					return restaurantList;
					
				}else{
					//Fail to find such restaurant
					if(Configuration.showLog){
						Log.d("RestaurantFetch","fetchAllRestaurant - Unable to find restaurant");
					}
				}
			}else{
				//unable to get response from server
				if(Configuration.showLog){
					Log.d("RestaurantFetch","fetchAllRestaurant - Unable to get response from server");
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			if(Configuration.showLog){
				Log.d("RestaurantFetch","fetchAllRestaurant - Exception");
			}
		}
		return null;
	}
	
	public String fetchRestaurantNameById(int id){
		//Get Json object
				// Building Parameters
		        params = new ArrayList<NameValuePair>();
		        params.add(new BasicNameValuePair("id",Integer.toString(id)));
		        
		        //Start a new thread and use POST method to send telephone and passcode to authURL
		        //Start a new thread to attempt Login (requirement when connecting online)
				Thread attemptThread = new Thread(new Runnable(){  
					public void run(){  
						result = jsonParser.makeHttpRequest(fetchRestaurantByIdURL,"POST",params);
					}
				});  
				attemptThread.start();
				
				while(attemptThread.isAlive()){
					//Wait for server response
				}
				
				//Parse the json object
				try {
					if(result.getString(KEY_STATUS) != null){
						//Able to get response from server
						if(result.getString(KEY_STATUS).equalsIgnoreCase(SUCCESS)){
							//Successful in finding the Restaurant
							if(Configuration.showLog){
								Log.d("RestaurantFetch","fetchRestaurantNameById - Restaurant found");
							}
							
							// Return the name of the restaurant
							return result.getString(KEY_NAME);
							
						}else{
							//Fail to find such restaurant
							if(Configuration.showLog){
								Log.d("RestaurantFetch","fetchRestaurantNameById - Unable to find restaurant");
							}
						}
					}else{
						//unable to get response from server
						if(Configuration.showLog){
							Log.d("RestaurantFetch","fetchRestaurantNameById - Unable to get response from server");
						}
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					//e.printStackTrace();
					if(Configuration.showLog){
						Log.d("RestaurantFetch","fetchRestaurantNameById - Exception");
					}
				}

				return null;
	}
}
